/*=========================================*/
// Init menu
/*=========================================*/
function initMenu(){
    $('#dBook').show();
    $('#dModels').hide();
    
}
/*=========================================*/
// initialize logbook grid
/*=========================================*/
function initLogbook(){
    $("#Logbook").jqGrid({
        url: 'php/server.php',
        datatype: 'json',
        height: "auto",
        width: "auto",
        colNames:['LogID','Date', 'Plane', 'N Number','From','To','Comment', 'Inst', 'Ldg'],
        colModel:[ 
            {name:'LogID', width:10, hidden: true}, 
            {name:'FD', index: 'FD', width:85, align:"center",sortable : true,editable:true}, 
            {name:'MakeName', index: 'MakeName', width:110, sortable : true},
            {name:'NNumber', index: 'NNumber', width:90, sortable : true},
            {name:'IdentFrom', index: 'IdentFrom', width:55, align:"right",sortable : true}, 
            {name:'IdentTo', index: 'IdentTo', width:55, align:"right", sortable : true}, 
            {name:'Comment', width:380,align:"left", sortable : false}, 
            {name:'InstrumentApproach', index: 'InstrumentApproach', width:32, align:"center", sortable : true},
            {name:'Landings', index: 'Landings', width:32, align:"center", sortable : true}
        ],
        onSelectRow: function (rowid) {
            //alert(rowid);
        },
        pager: '#pager',
        rowNum:10,
        rowList:[10,20,30],
        sortname: 'FD',
        sortorder: 'desc',
        viewrecords: true, 
        gridview: true,
        caption:"Pilot logbook"
    });
    $("#Logbook").jqGrid('navGrid','#pager',
        {edit:false,add:false,del:false}
    );
}

/*=========================================*/
// initialize datepicker
/*=========================================*/
$(function() {
    $( "#datepicker" ).datepicker({
        startDate:'05/28/2003',
        changeYear: true,
        changeMonth: true,
        buttonImage: 'image/cal.gif',
        showOn: 'button'
    });
});
/*=========================================*/
// Clear entry fields
/*=========================================*/
function ClearFields(){
    $('#datepicker').attr('value','');
    $("#Plane option").eq(0).attr('selected', 'selected');
    $('#NNumber option').each(function(i,e){
        $(e).remove();
    });
    $('#NNumber').append($("<option></option>"));
    $("#From option").eq(0).attr('selected', 'selected');
    $("#To option").eq(0).attr('selected', 'selected');
    $('#Comment').attr('value','');
    $('#Instr').attr('value','');
    $('#Ldg').attr('value','');
    // second row - details
    $('#cmplx').attr('checked','');
    $('#tsel').attr('value','');
    $('#tmel').attr('value','');
    $('#tday').attr('value','');
    $('#tnight').attr('value','');
    $('#isim').attr('value','');
    $('#iactual').attr('value','');
    $('#ground').attr('value','');
    $('#tpic').attr('value','');
    $('#tsic').attr('value','');
    $('#tsolo').attr('checked','checked');
    $('#tdual').attr('checked','');
}
/*=========================================*/
// Load Planes from server
/*=========================================*/
function LoadPlanes(){
    var sURL = "php/Loadplanes.php";
    $.ajax({
        url: sURL,
        type: "GET",
        processData: false,
        async: true,
        contentType: "application/json",
        dataType: "json",
        error: (function (returnedData) {
            alert("Load planes error");
        }),
        success: function (returnedData){
            //alert(returnedData);
            $('#tmplSelect').tmpl(returnedData).appendTo('#Plane');
            $('#tmplSelect').tmpl(returnedData).appendTo('#ddModel');
        }
    });
}
/*=========================================*/
// Init change Planes handler
/*=========================================*/
function initChangePlanes(){
    $('#Plane').change( function () {
        if ($(this).val() == ''){
            $('#NNumber option').each(function(i,e){
                $(e).remove();
            });
            $('#NNumber').append($("<option></option>"));
            return false;
        }
        LoadNNumbers();
    });
    return true;
}

/*=========================================*/
// Read Airports from server
/*=========================================*/
function LoadAirports(){
    var sURL = "php/Loadairports.php";
    $.ajax({
        url: sURL,
        type: "GET",
        processData: false,
        async: true,
        contentType: "application/json",
        dataType: "json",
        error: (function (returnedData) {
            alert("Load airports error");
        }),
        success: function (returnedData){
            $('#tmplSelect').tmpl(returnedData).appendTo('#From');
            $('#tmplSelect').tmpl(returnedData).appendTo('#To');                        
        }
    });
}

/*=========================================*/
// Load NNumbers for selected planes
/*=========================================*/
function LoadNNumbers(){
    var sURL = "php/LoadNNumbers.php?Make=" + $('#Plane').val();
    $.ajax({
        url: sURL,
        type: "GET",
        processData: false,
        async: true,
        contentType: "application/json",
        dataType: "json",
        error: (function (returnedData) {
            alert("Load NNumbers error");
        }),
        success: function (returnedData){
            var option = $('<option>');
            $(option).attr('value','');
            $('#NNumber').html('');
            $(option).appendTo('#NNumber');
            $('#tmplSelect').tmpl(returnedData).appendTo('#NNumber');
        }
    });                
}

/*=========================================*/
// Init main entry dialog
/*=========================================*/
function initLogEntryDialog(){
    $("#dialog").dialog({
        width: 1000,
        modal: true,
        autoOpen: false,
        buttons: [
            {
                text: "Submit",
                click: function () {
                    // validate fields
                    //if (ValidateFields() == false)
                    //    return false;
                    // format fiels value default
                    FormatFields();
                    // insert new record
                    InsertLog();
                    //ClearFields();
                    $("#Logbook").trigger("reloadGrid");
                }
            },
            {
                text: "Close",
                click: function() {$(this).dialog("close");}
            },
        ]
    });
}

/*=========================================*/
// Init models entry dialog
/*=========================================*/
function initModelsEntryDialog(){
    $("#Modelsdialog").dialog({
        width: "auto",
        modal: true,
        autoOpen: false,
        buttons: [
            {
                text: "Submit",
                click: function () {
                }
            },
            {
                text: "Close",
                click: function() {$(this).dialog("close");}
            },
        ]
    });
}

/*=========================================*/
// Init nnumbers entry dialog
/*=========================================*/
function initNNumbersEntryDialog(){
    $("#NNumbersdialog").dialog({
        width: "auto",
        modal: true,
        autoOpen: false,
        buttons: [
            {
                text: "Submit",
                click: function () {
                    if (NNumberExists() == false)
                        InsertNNumber();
                    else
                        alert("Number already in databse");
                    $("#NNumbers").trigger("reloadGrid");
                    $(this).dialog("close");
                }
            },
            {
                text: "Close",
                click: function() {$(this).dialog("close");}
            },
        ]
    });
}


/*=========================================*/
// Validate fields
/*=========================================*/
function ValidateFields(){
    var greenlight = true;
    // validate inputs
    $('.fValid').each(function(i,e){
        if($(e).val() == ''){
            //$(e).css('background-color','red');  // future validator development
            greenlight = false;
        }
    });
    // validate select fields
    if ($('#Plane option:selected').val() == '')
        greenlight = false;
    if ($('#NNumber option:selected').val() == '')
        greenlight = false;
    if ($('#From option:selected').val() == '')
        greenlight = false;
    if ($('#To option:selected').val() == '')
        greenlight = false;
    // validate second row
    if ($('#tsel').val() == '' && $('#tmel').val() == '')
        greenlight = false;
    if ($('#tday').val() == '' && $('#tnight').val() == '')
        greenlight = false;
    return (greenlight);
}

/*=========================================*/
// Format fields
/*=========================================*/
function FormatFields(){
    if ($('#Instr').val() == '')
        $('#Instr').attr('value','0');
    if ($('#tsel').val() == ''){
        $('#tsel').attr('value','0');
    }
    if  ($('#tmel').val() == ''){
        $('#tmel').attr('value','0');
    }
    if ($('#tday').val() == ''){
        $('#tday').attr('value','0');
    }
    if ($('#tnight').val() == ''){
        $('#tnight').attr('value','0');
    }
    if ($('#isim').val() == '')
        $('#isim').attr('value','0');
    if ($('#iactual').val() == '')
        $('#iactual').attr('value','0');
    if ($('#ground').val() == '')
        $('#ground').attr('value','0');
    if ($('#tpic').val() == '')
        $('#tpic').attr('value','0');
    if ($('#tsic').val() == '')
        $('#tsic').attr('value','0');
}

/*=========================================*/
// Insert new Log book entry
/*=========================================*/
function InsertLog() {
    var sUrl = 'php/AjaxHandler.php';
    var fields = '?cmd=Insert&Datepick=\'' + $('#datepicker').val() + '\'&plane=' + $('#Plane').val();
    fields += '&NNumber=' + $('#NNumber option:selected').attr('text');
    fields += '&From=' + $('#From').val();
    fields += '&To=' + $('#To').val();
    fields += '&Comment=\'' + $('#Comment').val() + '\'';
    fields += '&Instr=' + $('#Instr').val();
    fields += '&Ldg=' + $('#Ldg').val();
    fields += '&cmplx=' + $('#cmplx').attr('checked');
    fields += '&tsel=' + $('#tsel').val();
    fields += '&tmel=' + $('#tmel').val();
    fields += '&tday=' + $('#tday').val();
    fields += '&tnight=' + $('#tnight').val();
    fields += '&isim=' + $('#isim').val();
    fields += '&iactual=' + $('#iactual').val();
    fields += '&ground=' + $('#ground').val();
    fields += '&tpic=' + $('#tpic').val();
    fields += '&tsic=' + $('#tsic').val();
    if ($('#tsolo').attr('checked') == true)
        fields += '&solodual=1';
    else
        fields += '&solodual=0';
    sUrl += fields;
    //return false;
    $.ajax({
        url: sUrl,
        async: false,
        success: function (returnData){
            //alert(returnData);
        },
        error: function(message){
            alert(message);
        }
    });
    return true;
}

/*=========================================*/
// init models grid
/*=========================================*/
function initModels(){
    $("#Models").jqGrid({
        url: 'php/loadplanesgrid.php',
        datatype: 'json',
        height: "auto", 
        colNames:['makeID','CategoryID', 'Category', 'Model', 'Comment'],
        colModel:[ 
            {name:'makeID', width:10, hidden: true},
            {name:'CategoryID', hidden: true}, 
            {name:'CatName', index: 'CatName', width:80, sortable : true},
            {name:'Name', index: 'Name', width:110, sortable : true},
            {name:'Comment', index: 'Comment', width:380, sortable : true}
        ],
        pager: '#Modelspager',
        rowNum:30,
        rowList:[10,20,30],
        sortname: 'Category',
        sortorder: 'ASC',
        viewrecords: true,
        gridview: true,
        caption:"Models"
    });
}

/*=========================================*/
// init categories grid
/*=========================================*/
function initCategories(){
//    var sUrl = 'php/loadcategoriesgrid.php';
//    //alert(sUrl);
//    $.ajax({
//       url: sUrl,
//        type: "GET",
//        processData: false,
//        contentType: "application/json",
//        dataType: "text",
//        async: true,
//        success: function (returnedData){
//            alert(returnedData);
//        },
//        error: function (message){
//            alert(message);
//        }
//       
//    });
   $("#Categories").jqGrid({
        url: 'php/loadcategoriesgrid.php',
        datatype: 'json',
        height: "auto", 
        colNames:['CategoryID', 'Category', 'Comment'],
        colModel:[ 
            {name:'CategoryID', hidden: true}, 
            {name:'Name', width:80},
            {name:'Comment', width:380}
        ],
        viewrecords: true,
        gridview: true,
        caption:"Categories"
    }); 
}

/*=========================================*/
// init NNumbers grid
/*=========================================*/
function initNNumbers(){
    // load grid
    $("#NNumbers").jqGrid({
        url: 'php/loadnnumbersgrid.php',
        datatype: 'json',
        height: "auto",
        width: 550,
        colNames:['AircraftID','Category', 'Model', 'N-Number', 'Comment'],
        colModel:[ 
            {name:'AircraftID', width:10, hidden: true},
            {name:'CatName', index: 'CatName', width:80, sortable : true},
            {name:'MName', index: 'MName', width:110, sortable : true},
            {name:'NNumber', index: 'NNumber', width:90, sortable : true},
            {name:'Comment', index: 'Comment', width:380, sortable : true}
        ],
        pager: '#NNumberspager',
        rowNum:30,
        rowList:[10,20,30],
        sortname: 'Category',
        sortorder: 'ASC',
        viewrecords: true,
        gridview: true,
        caption:"Tail numbers"
    });
    $("#ddModel option").eq(0).attr('selected', 'selected');
}

/*=========================================*/
// init category select
/*=========================================*/
function initCategorySelect(){
    var sURL = "php/AjaxHandler.php?cmd=category";
    $.ajax({
        url: sURL,
        type: "GET",
        async: false,
        contentType: "application/json",
        dataType: "json",
        error: (function () {
            alert("Load categories error");
        }),
        success: function (returnedData){
            $('#tmplSelect').tmpl(returnedData).appendTo('#ddCategory');
        }
    });
    $("#ddCategory option").eq(0).attr('selected', 'selected');    
}

/*=========================================*/
// Check if nnumber exists
/*=========================================*/
function NNumberExists(){
    var numberexists = false;
    var sUrl = 'php/AjaxHandler.php';
    var fields = '?cmd=NNumberExists&nnumber=\'' + $('#nnumber').val() + '\'';
    $.ajax({
        url: sUrl + fields,
        async: false,
        success: function (returnData){
            if (returnData != '')
                numberexists = true;
            //alert(returnData);
        },
        error: function(message){
            alert(message);
        }
    });
    return numberexists;
}

/*=========================================*/
// Insert NNumber
/*=========================================*/
function InsertNNumber(){
    var sUrl = 'php/AjaxHandler.php';
    var fields = '?cmd=InsertNNumber&makeid=' + $('#ddModel').val() + '&nnumber=\'' + $('#nnumber').val();
    fields += '\'&comment=\'' + $('#nComment').val() + "\'";
    $.ajax({
        url: sUrl + fields,
        async: false,
        success: function (returnData){
            //alert(returnData);
        },
        error: function(message){
            //alert(message);
        }
    });
    $("#ddCategory option").eq(0).attr('selected', 'selected');
    $("#ddModel option").eq(0).attr('selected', 'selected');
    $('#nnumber').attr('value','');
    $('#nComment').html('');
}
